//
//  FrontCameraViewController.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/2/26.
//


#import "FrontCameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <Masonry.h>
#import <YYKit.h>

@interface FrontCameraViewController ()<AVCapturePhotoCaptureDelegate>
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCapturePhotoOutput *photoOutput;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
//@property (nonatomic, assign) AVCaptureDevicePosition currentCameraPosition;
@property (nonatomic, strong) UIButton *switchCameraButton;

@property (nonatomic, strong) UIView *liveview;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *captureButton;

@property (nonatomic, strong) UIImageView *preview;
@property (nonatomic, strong) UIButton *leftButton;
@property (nonatomic, strong) UIButton *rightButton;
@end

@implementation FrontCameraViewController
@synthesize switchCameraButtonHidden = _switchCameraButtonHidden;

- (instancetype)init {
    if (self = [super init]) {
        _switchCameraButtonHidden = YES;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self showNavBar:@""];
    self.navBar.backgroundColor = UIColor.clearColor;
    
    // 检查相机权限
    [self checkCameraPermission];
    
    [self setupViews];
}

- (void)setupViews {
    [self.view addSubview:self.liveview];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.captureButton];
    [self.view addSubview:self.switchCameraButton];
    
    [self.liveview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
    }];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.liveview.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(120);
    }];
    [self.captureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.bottomView);
        make.width.height.mas_equalTo(60);
    }];
    [self.switchCameraButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-20);
        make.top.equalTo(self.view).offset(SAFE_AREA_INSETS.top + 20);
        make.width.height.mas_equalTo(44);
    }];
    
    [self.view addSubview:self.preview];
    [self.preview addSubview:self.leftButton];
    [self.preview addSubview:self.rightButton];
    [self.preview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [self.leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.bottom.equalTo(self.view).inset(SAFE_AREA_INSETS.bottom+20);
        make.width.mas_equalTo(self.leftButton.intrinsicContentSize.width+20*2);
        make.height.mas_equalTo(30);
    }];
    [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).inset(20);
        make.bottom.equalTo(self.view).inset(SAFE_AREA_INSETS.bottom+20);
        make.width.mas_equalTo(self.rightButton.intrinsicContentSize.width+20*2);
        make.height.mas_equalTo(30);
    }];
    [self.view layoutIfNeeded];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.previewLayer.frame = self.liveview.bounds;
}

- (void)checkCameraPermission {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    [self setupCamera];
                } else {
                    [self showCameraPermissionAlert];
                }
            });
        }];
    } else if (status == AVAuthorizationStatusAuthorized) {
        [self setupCamera];
    } else {
        [self showCameraPermissionAlert];
    }
}

- (void)showCameraPermissionAlert {
    NSString *message = @"For a smooth identity verification, please allow SulitLoan to access your camera. This lets you upload required documents and complete facial recognition easily. Enable camera permissions in \"Settings.\"";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Require camera permissions"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"Go to settings"
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]
                                           options:@{}
                                 completionHandler:nil];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel"
                                                           style:UIAlertActionStyleCancel
                                                         handler:nil];
    
    [alert addAction:settingsAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (UIView *)liveview {
    if (!_liveview) {
        _liveview = [UIView new];
    }
    return _liveview;
}
- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [UIView new];
        _bottomView.backgroundColor = UIColor.blackColor;
    }
    return _bottomView;
}
- (UIButton *)captureButton {
    if (!_captureButton) {
        _captureButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _captureButton.backgroundColor = UIColor.whiteColor;
        _captureButton.layer.cornerRadius = 30;
        [_captureButton addTarget:self action:@selector(takePhoto:) forControlEvents:UIControlEventTouchUpInside];
        
        // 添加点击反馈
        [_captureButton addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_captureButton addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpOutside | UIControlEventTouchCancel];
    }
    return _captureButton;
}

- (UIImageView *)preview {
    if (!_preview) {
        _preview = [UIImageView new];
        _preview.contentMode = UIViewContentModeScaleAspectFill;
        _preview.hidden = YES;
        _preview.userInteractionEnabled = YES;
    }
    return _preview;
}
- (UIButton *)leftButton {
    if (!_leftButton) {
        _leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_leftButton setTitle:@"Retake" forState:UIControlStateNormal];
        @weakify(self);
        [_leftButton jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @strongify(self);
            self.preview.hidden = YES;
        }];
    }
    return _leftButton;
}
- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton setTitle:@"Use Photo" forState:UIControlStateNormal];
        @weakify(self);
        [_rightButton jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @strongify(self);
            !self.captureCallback ?: self.captureCallback(self.preview.image);
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
    return _rightButton;
}

- (UIButton *)switchCameraButton {
    if (!_switchCameraButton) {
        _switchCameraButton = [UIButton buttonWithType:UIButtonTypeCustom];
        if (@available(iOS 13.0, *)) {
            [_switchCameraButton setImage:[UIImage systemImageNamed:@"camera.rotate.fill"] forState:UIControlStateNormal];
        }
        _switchCameraButton.tintColor = UIColor.whiteColor;
        [_switchCameraButton addTarget:self action:@selector(switchCamera) forControlEvents:UIControlEventTouchUpInside];
        
        // 添加点击反馈
        [_switchCameraButton addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_switchCameraButton addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpOutside | UIControlEventTouchCancel];
        _switchCameraButton.hidden = self.switchCameraButtonHidden;
    }
    return _switchCameraButton;
}

- (void)setSwitchCameraButtonHidden:(BOOL)switchCameraButtonHidden {
    _switchCameraButtonHidden = switchCameraButtonHidden;
    self.switchCameraButton.hidden = switchCameraButtonHidden;
}
- (BOOL)switchCameraButtonHidden {
    return _switchCameraButtonHidden;
}

- (void)setupCamera {
    self.session = [[AVCaptureSession alloc] init];
    self.session.sessionPreset = AVCaptureSessionPresetPhoto;
    
    AVCaptureDevicePosition position = (self.currentCameraPosition == AVCaptureDevicePositionFront) ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
    AVCaptureDevice *frontCamera = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera mediaType:AVMediaTypeVideo position:position];
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error];
    if (!input) {
        NSLog(@"Error: %@", error);
        return;
    }
    if ([self.session canAddInput:input]) {
        [self.session addInput:input];
    }
    
    self.photoOutput = [[AVCapturePhotoOutput alloc] init];
    if ([self.session canAddOutput:self.photoOutput]) {
        [self.session addOutput:self.photoOutput];
    }
    
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    //self.previewLayer.frame = self.view.bounds;
    //[self.view.layer addSublayer:self.previewLayer];
    self.previewLayer.frame = self.liveview.bounds;
    [self.liveview.layer addSublayer:self.previewLayer];
    
    [self.session startRunning];
}
- (void)switchCamera {
    // 获取当前设备方向
    AVCaptureDevicePosition newPosition = (self.currentCameraPosition == AVCaptureDevicePositionFront) ? AVCaptureDevicePositionBack : AVCaptureDevicePositionFront;
    
    // 获取新的摄像头设备
    AVCaptureDevice *newCamera = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera
                                                                    mediaType:AVMediaTypeVideo
                                                                     position:newPosition];
    
    // 创建新的输入设备
    NSError *error = nil;
    AVCaptureDeviceInput *newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:&error];
    
    if (error) {
        NSLog(@"Error creating capture device input: %@", error.localizedDescription);
        return;
    }
    
    // 禁用切换按钮，防止快速点击
    self.switchCameraButton.enabled = NO;
    
    // 添加切换动画
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5;
    animation.type = @"oglFlip";
    animation.subtype = kCATransitionFromRight;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.previewLayer addAnimation:animation forKey:@"flipAnimation"];
    
    // 在session中切换输入设备
    [self.session beginConfiguration];
    
    // 移除旧的输入设备
    AVCaptureInput *currentInput = [self.session.inputs firstObject];
    [self.session removeInput:currentInput];
    
    // 添加新的输入设备
    if ([self.session canAddInput:newInput]) {
        [self.session addInput:newInput];
        self.currentCameraPosition = newPosition;
    }
    
    [self.session commitConfiguration];
    
    // 延迟启用切换按钮
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.switchCameraButton.enabled = YES;
    });
}

- (void)takePhoto:(id)sender {
    AVCapturePhotoSettings *settings = [AVCapturePhotoSettings photoSettings];
    [self.photoOutput capturePhotoWithSettings:settings delegate:self];
}

- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error {
    if (error) {
        NSLog(@"Error: %@", error);
        return;
    }
    NSData *imageData = [photo fileDataRepresentation];
    UIImage *image = [UIImage imageWithData:imageData];
    // 处理拍摄的照片
    
    self.preview.image = image;
    self.preview.hidden = NO;
}

- (void)buttonTouchDown:(UIButton *)button {
    [UIView animateWithDuration:0.1 animations:^{
        button.transform = CGAffineTransformMakeScale(0.9, 0.9);
        button.alpha = 0.8;
    }];
}

- (void)buttonTouchUp:(UIButton *)button {
    [UIView animateWithDuration:0.1 animations:^{
        button.transform = CGAffineTransformIdentity;
        button.alpha = 1.0;
    }];
}

@end
